package com.mike.mybatis;

import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

public abstract class AbstractMysqlDao<T> extends SqlSessionDaoSupport implements SqlBaseDao<T>, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public T one() {
        return ((MysqlMapper<T>)(this.getSqlSession().getMapper(this.mapperClass()))).one();
    }

    @Override
    protected void checkDaoConfig() {
        String template = null;
        SqlSessionTemplate sqlSessionTemplate;
        if (!StringUtils.isEmpty(template)) {
            sqlSessionTemplate = (SqlSessionTemplate) this.applicationContext.getBean(template);
            this.setSqlSessionTemplate(sqlSessionTemplate);
        } else {
            sqlSessionTemplate = (SqlSessionTemplate) this.applicationContext.getBean(SqlSessionTemplate.class);
            this.setSqlSessionTemplate(sqlSessionTemplate);
        }

        DBSql.register(this);
        super.checkDaoConfig();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    protected abstract Class mapperClass();
}
